package com.ciwong.epaper.modules.reciteWords.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.util.AddPointTypes;
import com.ciwong.epaper.modules.reciteWords.bean.LearnCountBean;
import com.ciwong.epaper.modules.reciteWords.bean.PlanAndWorListBean;
import com.ciwong.epaper.modules.reciteWords.dao.WordDao;
import com.ciwong.epaper.modules.reciteWords.util.WordUtil;
import com.ciwong.epaper.modules.reciteWords.widget.sign.SignAdapter;
import com.ciwong.epaper.modules.reciteWords.widget.sign.SignEntity;
import com.ciwong.epaper.modules.reciteWords.widget.sign.SignView;
import com.ciwong.epaper.modules.share.QQShareHelper;
import com.ciwong.epaper.modules.share.QQShareListener;
import com.ciwong.epaper.modules.share.WxShareHelper;
import com.ciwong.epaper.modules.share.WxShareListener;
import com.ciwong.epaper.modules.share.bean.ShareMsgObj;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DateUtils;
import com.ciwong.epaper.util.DoubleClickCheckUtils;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.ShowViewType;
import com.ciwong.epaper.util.Xml2BitmapUtils;
import com.ciwong.epaper.widget.WordPlanNumberView;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.epaper.utils.PxUtils;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.UiError;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by keepon on 2018/9/19.
 */
public class DaKaActivity extends BaseActivity implements View.OnClickListener {
    SignView mSignView;
    TextView mTvMonth;
    TextView mTvShareText;
    ScrollView mScrollView;
    LinearLayout mLlNoNet,mLlGetDataFailed;
    Button mBtnRetry,mBtnFailedRetry;
    WordPlanNumberView mWordPlanNumberViewDays, mWordPlanNumberViewDaysCount;
    ImageView shareWeixinFriend, shareWeixin, shareQQ, shareQQSpace;
    private ArrayList<SignEntity> mData;
    private ArrayList<Integer> mWordIndexArray;
    private LearnCountBean learnCountBeanInfor;

    @Override
    protected int setView() {
        return R.layout.activity_daka;
    }

    @Override
    protected void findViews() {
        mTvMonth = findViewById(R.id.tv_month);
        mSignView = findViewById(R.id.sign_view);
        mTvShareText = findViewById(R.id.tv_share_text);
        mScrollView = findViewById(R.id.scroll_view);
        mLlNoNet = findViewById(R.id.ll_no_net);
        mLlGetDataFailed = findViewById(R.id.ll_get_data_failed);
        mBtnRetry = findViewById(R.id.btn_retry);
        mBtnFailedRetry = findViewById(R.id.btn_failed_retry);
        mWordPlanNumberViewDays = findViewById(R.id.word_plan_days);
        mWordPlanNumberViewDaysCount = findViewById(R.id.word_plan_days_count);
        shareWeixinFriend = findViewById(R.id.share_weixin_friend);
        shareWeixin = findViewById(R.id.share_weixin);
        shareQQ = findViewById(R.id.share_qq);
        shareQQSpace = findViewById(R.id.share_qq_space);
        shareQQSpace.setVisibility(View.GONE);
        mTvShareText.setText("打卡到");
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        if (DateUtils.isFirstDayOfMonthIsSunDay(year, month)) {
            int height = PxUtils.dip2px(DaKaActivity.this, 285);
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height);
            layoutParams.addRule(RelativeLayout.BELOW, R.id.tv_month);
            mSignView.setLayoutParams(layoutParams);
        }


    }

    @Override
    protected void initEvent() {
        mBtnRetry.setOnClickListener(this);
        mBtnFailedRetry.setOnClickListener(this);
        shareWeixinFriend.setOnClickListener(this);
        shareWeixin.setOnClickListener(this);
        shareQQ.setOnClickListener(this);
        shareQQSpace.setOnClickListener(this);

    }

    @Override
    protected void init() {
        isSupportQQAndQQZone();
        setBackImg(R.mipmap.icon_x_exit);
        setValideSource(false);
        Intent intent = getIntent();
        if (intent != null) {
            mWordIndexArray = (ArrayList<Integer>) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_WORD_INDEX_ARRAY);
        }

        mData = new ArrayList<>();
        String monthString = DateUtils.getMonthString();
        String yearString = DateUtils.getYear() + "";
        mTvMonth.setText(monthString + " " + yearString);
        if (mWordIndexArray == null) {
            getDataFromNet();
        } else {
            submitWord(mWordIndexArray);
        }


    }

    private void setData(LearnCountBean learnCountBean) {
        if (learnCountBean == null) {
            return;
        }
        try {
            mWordPlanNumberViewDays.setCount(learnCountBean.getCountDay());
            mWordPlanNumberViewDaysCount.setCount(learnCountBean.getDayCount());
            List<Integer> dateIndexArr = learnCountBean.getDateIndexArr();
            int daysCountOfMonth = DateUtils.getDaysCountOfMonth();
            for (int i = 0; i < daysCountOfMonth; i++) {
                SignEntity signEntity = new SignEntity();

                if (dateIndexArr != null) {
                    if (dateIndexArr.contains(i)) {
                        signEntity.setDayType(SignView.DayType.SIGNED);
                    } else {
                        signEntity.setDayType(SignView.DayType.UNSIGNED);
                    }
                } else {
                    signEntity.setDayType(SignView.DayType.UNSIGNED);
                }
                mData.add(signEntity);
            }
            SignAdapter signAdapter = new SignAdapter(mData);
            mSignView.setAdapter(signAdapter);
        }catch (Exception e){

        }

    }

    private void getDataFromNet() {
        showCricleProgress();
        int userId = (int) EApplication.getInstance().getUserInfoBase().getUserId();
        WordDao.getInstance().getLearnCount(userId, new BaseExtCallBack(DaKaActivity.this) {
            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode,data);
                showDataView(ShowViewType.VIEW_TYPE_FAILED_ERROR);
                hideCricleProgress();
            }

            @Override
            public void failed(Object data) {
                super.failed(data);
                showDataView(ShowViewType.VIEW_TYPE_NO_NET_ERROR);
                hideCricleProgress();
            }

            @Override
            public void success(Object data) {
                showDataView(ShowViewType.VIEW_TTPE_DATA);
                hideCricleProgress();
                if (data != null && data instanceof LearnCountBean) {
                    LearnCountBean learnCountBean = (LearnCountBean) data;
                    learnCountBeanInfor= makeDaKaInfor(learnCountBean);
                    setData(learnCountBean);
                }
                //获取积分
                MeDao.getInstance().getUserPoint();
            }
        });
    }

    @Override
    protected void loadData() {

    }

    public void showDataView(ShowViewType showViewType) {
        if (showViewType ==ShowViewType.VIEW_TTPE_DATA) {
            mScrollView.setVisibility(View.VISIBLE);
            mLlNoNet.setVisibility(View.GONE);
            mLlGetDataFailed.setVisibility(View.GONE);
        } else if (showViewType ==ShowViewType.VIEW_TYPE_NO_NET_ERROR)  {
            mScrollView.setVisibility(View.GONE);
            mLlNoNet.setVisibility(View.VISIBLE);
            mLlGetDataFailed.setVisibility(View.GONE);
        }else{
            mScrollView.setVisibility(View.GONE);
            mLlNoNet.setVisibility(View.GONE);
            mLlGetDataFailed.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View v) {
        if (!DoubleClickCheckUtils.vertify500Duration()) {
            return;
        }

        int id = v.getId();
        if (id == R.id.btn_retry||id == R.id.btn_failed_retry) {
            if (mWordIndexArray == null) {
                getDataFromNet();
            } else {
                submitWord(mWordIndexArray);
            }
        }
        else{
            Xml2BitmapUtils.saveCroppedImage(DaKaActivity.this, learnCountBeanInfor);
            if (id == R.id.share_weixin_friend) {
                weChatShare(2);
            } else if (id == R.id.share_weixin) {
                weChatShare(1);
            } else if (id == R.id.share_qq) {
                qqShare("QQ");
            } else if (id == R.id.share_qq_space) {
                qqShare("QZone");
            }
        }
    }

    private LearnCountBean makeDaKaInfor(LearnCountBean learnCountBean) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());
        String strDate = formatter.format(curDate);

        UserInfoBase userInfoBase = EApplication.getInstance().getUserInfoBase();
        String name="";
        String avatar="";
        if (userInfoBase!=null){
            String realName = userInfoBase.getRealName();
            if (TextUtils.isEmpty(realName)){
                String nickName = userInfoBase.getNickName();
                if (TextUtils.isEmpty(nickName)){
                    name= TextUtils.isEmpty(userInfoBase.getUserId()+"")?"" :userInfoBase.getUserId()+"";
                } else {
                    name=nickName;
                }
            }else {
                name=realName;
            }
            avatar = userInfoBase.getAvatar();
        }

        learnCountBean.setDate(strDate);
        learnCountBean.setUserName(name);
        learnCountBean.setHeadUrl(avatar);

        return learnCountBean;
    }

    private void submitWord(ArrayList<Integer> mWordIndexArray) {
        int userId = (int) EApplication.getInstance().getUserInfoBase().getUserId();
        showCricleProgress();
        WordDao.getInstance().submitWord(userId, mWordIndexArray, new BaseExtCallBack(DaKaActivity.this) {
            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode,data);
                hideCricleProgress();
                showDataView(ShowViewType.VIEW_TYPE_FAILED_ERROR);
            }

            @Override
            public void failed(Object data) {
                super.failed(data);
                hideCricleProgress();
                showDataView(ShowViewType.VIEW_TYPE_NO_NET_ERROR);
            }

            @Override
            public void success(Object data) {
                if (data != null && data instanceof PlanAndWorListBean) {
                    PlanAndWorListBean planAndWorListBean = (PlanAndWorListBean) data;
                    //提交成功更新BookId
                    CWSys.setSharedInt(ListenSpeakUtil.getCurrentPlanBookIdKey(), planAndWorListBean.getBookId());
                    WordUtil.clearStudyRecord();
                    getDataFromNet();
                } else {
                    hideCricleProgress();
                    showDataView(ShowViewType.VIEW_TYPE_FAILED_ERROR);
                }

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        WxShareHelper.getInstance().onResumeResultData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        WxShareHelper.getInstance().release();
        QQShareHelper.getInstance().release();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_QQ_SHARE || requestCode == Constants.REQUEST_QZONE_SHARE) {
            QQShareHelper.getInstance().onActivityResultData(requestCode, resultCode, data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    public void isSupportQQAndQQZone() {
        if (EConstants.QQ_APP_ID.equals("") || null == EConstants.QQ_APP_ID) {
            shareQQ.setImageResource(R.mipmap.share_qq_unstalled);
            shareQQSpace.setImageResource(R.mipmap.share_qq_space_unstalled);
            shareQQ.setEnabled(false);
            shareQQSpace.setEnabled(false);
        }

    }

    /**
     * 1代表分享给好友，2代表分享到朋友圈
     *
     * @param wxType
     */
    private void weChatShare(int wxType) {
        int bmpThunbWith = 80;
        int bmpThunbHigh = 80;
        try {
            WxShareHelper.getInstance().initWxShare(DaKaActivity
                    .this, new WxShareListener() {
                @Override
                public void onWxShareing(String str) {

                    Log.d("sharetest", "##########onWxShareing######" + str);
                }

                @Override
                public void onWxShareSucc(String var) {
                        shareAddPointType(AddPointTypes.SHERE_FIRST_MEMORIZING_WORDS);
//                    ToastCustomView.getInstance().toastShowCenterSuccess(EApplication.getInstance().getResources().getString(R.string.share_success_daka), Toast.LENGTH_SHORT);
                    Log.d("sharetest", "##########onWxShareSucc######" + var);
                }

                @Override
                public void onWxShareFailure(int var, String var1) {
                    Log.d("sharetest", "##########onWxShareFailure######" + var1);
                }

                @Override
                public boolean onWxShareCancel() {
                    ToastUtil.INSTANCE.toastCenter(EApplication.getInstance(), EApplication.getInstance().getResources().getString(R.string.share_fail_daka), R.mipmap.ic_cancel);
                    Log.d("sharetest", "##########onWxShareCancel######");
                    return true;
                }
            });
            ShareMsgObj shareMsgObj = new ShareMsgObj();
            shareMsgObj.setWxType(wxType);
            shareMsgObj.setShareType(ShareMsgObj.ShareType.SHARE_IMAGE);
            Bitmap bmp = BitmapFactory.decodeFile(FileUtil.getShareReciteWordIconLocalPath(getApplicationContext()));
            Bitmap bmpThunb = Bitmap.createScaledBitmap(bmp, bmpThunbWith, bmpThunbHigh, true);
            shareMsgObj.setThunbBmp(bmpThunb);
            shareMsgObj.setBmp(bmp);
            WxShareHelper.getInstance().sendReq(shareMsgObj);
        } catch (Exception e) {
            e.getStackTrace();
        }
    }


    /**
     * "QQ"代表分享给QQ好友，"QZone"代表分享到QQ空间
     *
     * @param qq
     */

    private void qqShare(String qq) {
        try {
            ShareMsgObj shareMsgObj = new ShareMsgObj();
            shareMsgObj.setShareType(ShareMsgObj.ShareType.SHARE_IMAGE);
            shareMsgObj.setLocalImgUrl(FileUtil.getShareReciteWordIconLocalPath(getApplicationContext()));
            shareMsgObj.setText(getResources().getString(R.string.app_name));
            if (qq.equals("QQ")) {
                QQShareHelper.getInstance().shareToQQ(DaKaActivity
                        .this, shareMsgObj, new QQShareListener() {
                    @Override
                    public void onQQShareSucc(Object var) {
                        shareAddPointType(AddPointTypes.SHERE_FIRST_MEMORIZING_WORDS);
//                        ToastCustomView.getInstance().toastShowCenterSuccess(EApplication.getInstance().getResources().getString(R.string.share_success_daka), Toast.LENGTH_SHORT);
                        System.out.println("分享成功：onQQShareSucc " + var);
                    }

                    @Override
                    public void onQQShareFailure(UiError var1) {
                        System.out.println("分享失败：onQQShareFailure " + var1);
                    }

                    @Override
                    public boolean onQQShareCancel() {
                        ToastUtil.INSTANCE.toastCenter(EApplication.getInstance(), EApplication.getInstance().getResources().getString(R.string.share_fail_daka), R.mipmap.ic_cancel);
                        System.out.println("分享取消：onQQShareCancel");
                        return true;
                    }
                });
            } else if (qq.equals("QZone")) {
                QQShareHelper.getInstance().shareToQZone(DaKaActivity.this, shareMsgObj, new QQShareListener() {
                    @Override
                    public void onQQShareSucc(Object var) {
                        shareAddPointType(AddPointTypes.SHERE_FIRST_MEMORIZING_WORDS);
//                        ToastCustomView.getInstance().toastShowCenterSuccess(EApplication.getInstance().getResources().getString(R.string.share_success_daka), Toast.LENGTH_SHORT);
                        System.out.println("分享成功：onQQShareSucc " + var);
                    }

                    @Override
                    public void onQQShareFailure(UiError var1) {
                        System.out.println("分享失败：onQQShareFailure " + var1);
                    }

                    @Override
                    public boolean onQQShareCancel() {
                        ToastUtil.INSTANCE.toastCenter(EApplication.getInstance(), EApplication.getInstance().getResources().getString(R.string.share_fail_daka), R.mipmap.ic_cancel);
                        System.out.println("分享取消：onQQShareCancel");
                        return true;
                    }
                });
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
    }
    private void shareAddPointType(String type) {
        MeDao.getInstance().addPoint(EApplication.getInstance().getUserInfoBase().getUserId() + "", EApplication.getInstance().getUserInfoBase().getRealName(), type, null);
    }


}
